package com.Webserver.core;

import com.Webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一次交互有三步构成:
 * 1:解析请求
 * 2:处理请求
 * 3:响应客户端
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {

        try {
            /** 1.解析请求 */
            HttpRequest request =new HttpRequest(socket);
            /** 2.处理请求 */

            String path = request.getUri();
            File file = new File("./webapps"+path);
            /** 3.发送响应 */
            OutputStream out = socket.getOutputStream();
            //3.1发送状态行
            String line = "HTTP/1.1 200 OK";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            //3.2发送响应头
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            //单独发送CRLF表示响应头发送完毕.
            out.write(13);
            out.write(10);
            //3.3:发生响应正文
            FileInputStream fis = new FileInputStream(file);
            data = new byte[1024*10];
            int num;
            while ( (num=fis.read(data))!=-1 ){
                out.write(data,0,num);
            }
            System.out.println("加载成功!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //一次HTTP交互完毕后要与客户端断开连接(HTTP协议要求)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
